//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package api_common

import (
	"context"

	"gitcode.com/eteam/api-server/dao/board_dao"
)

/*
 * 离开画板
 *
 * 1. 删除画板成员
 * 2. 检查是否还有admin权限
 */

func LeaveBoard(ctx context.Context, boardId, memberUserId string) error {
	//删除画板成员
	err := board_dao.MemberInfoDao.Remove(ctx, boardId, memberUserId)
	if err != nil {
		return err
	}
	//检查是否还有成员
	count, err := board_dao.MemberInfoDao.CountByBoard(ctx, boardId)
	if err != nil {
		return err
	}
	if count == 0 {
		boardItem, err := board_dao.BoardInfoDao.Get(ctx, boardId)
		if err != nil {
			return err
		}
		err = board_dao.BoardInfoDao.Remove(ctx, boardId)
		if err != nil {
			return err
		}
		err = board_dao.RemoveBoardInfoDao.Insert(ctx, boardItem)
		if err != nil {
			return err
		}
		return nil
	}
	//检查是否有admin成员
	count, err = board_dao.MemberInfoDao.CountByAdmin(ctx, boardId, true)
	if err != nil {
		return err
	}
	if count == 0 {
		memberItemList, err := board_dao.MemberInfoDao.ListByBoard(ctx, boardId)
		if err != nil {
			return err
		}
		if len(memberItemList) > 0 {
			err = board_dao.MemberInfoDao.UpdateAdmin(ctx, boardId, memberItemList[0].MemberUserId, true)
			if err != nil {
				return err
			}
		}
	}
	return nil
}
